﻿using System;
using System.Collections.Generic;
using System.Linq;
using NHibernate.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JuCloudy.Data.Nhibernate
{
    public class SysErrorLogContainer
    {
        private static global::NHibernate.Cfg.Configuration mCfg = null;
        private static global::NHibernate.ISessionFactory SessionFactory = null;

        public SysErrorLogContainer()
        {
            mCfg = new NHibernate.Cfg.Configuration().Configure(
                System.Web.HttpContext.Current.Server.MapPath(
                     System.Configuration.ConfigurationManager.AppSettings["SysErrorLogNhCfg"]
                     ));

            SessionFactory = null;
            //mCfg.AddAssembly(Assembly.GetExecutingAssembly());
            mCfg.AddClass(typeof(JuCloudy.Data.Entity.SysErrorLog));
            SessionFactory = mCfg.BuildSessionFactory();
        }

        public void Insert(JuCloudy.Data.Entity.SysErrorLog entity)
        {
            entity.ReportDateTime = DateTime.Now;
            entity.ReportDateTimeStamp = JuCloudy.Data.timeStamp.ConvertDateTimeInt(entity.ReportDateTime);
            using (NHibernate.ISession session = SessionFactory.OpenSession())
            {
                using (NHibernate.ITransaction vTransaction = session.BeginTransaction())
                {
                    try
                    {
                        session.Save(entity);
                        vTransaction.Commit();
                        vTransaction.Dispose();
                        session.Flush();
                        session.Close();
                        session.Dispose();
                    }
                    catch (Exception ex)
                    {
                        vTransaction.Rollback();
                        vTransaction.Dispose();
                        session.Flush();
                        session.Close();
                        session.Dispose();
                        throw ex;
                    }
                }
            }
        }

        public List<JuCloudy.Data.Entity.SysErrorLog> GetEntities()
        {
            using (NHibernate.ISession session = SessionFactory.OpenSession())
            {
                var query = session.Query<JuCloudy.Data.Entity.SysErrorLog>().ToList();
                session.Flush();
                session.Close();
                session.Dispose();
                return query;
            }
        }

        
    }
}
